﻿using BCData.Common.News.NewsContent;
using BCData.MakeStaticPagingComponent.PageTemplate;
using BCDto.Common.WebsiteConfiguration;
using BCDto.MakeStaticPagingComponent.MakeStaticPaging;
using BCDto.MakeStaticPagingComponent.PageTemplate;
using BCEntity.MakeStaticPagingComponent.PageTemplate;
using BCParsePageExpression;
using BCService.MakeStaticPagingComponent.PageTemplateSerialize;
using BCService.MakeStaticPagingComponent.PageTemplateSerialize.HandleSaveFile;
using BCService.MakeStaticPagingComponent.PageTemplateSerialize.InitialiseSystemDefine;
using BCService.MakeStaticPagingComponent.PageTemplateSerialize.SerializeMethod;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace BCService.MakeStaticPagingComponent
{
    /// <summary>
    /// 构建静态页面服务
    /// </summary>
    public class MakeStaticPagingService : IMakeStaticPagingService
    {
        private readonly IPageTemplateData pageTemplateData;
        private readonly INewsContentData newsContentData;
        private readonly IPageTemplateSerializeService pageTemplateSerializeService;
        private readonly IInitialiseSystemDefineService initialiseSystemDefineService;
        private readonly ISerializeMethodService serializeMethodService;
        private readonly IHandleSaveFileService handleSaveFileService;
        private const int SYSTEMCONFIGURATIONID = 1;

        public WebsiteConfigurationDto WebsiteConfigurationDto { get; set; }

        public MakeStaticPagingService(IPageTemplateData pageTemplateData,
            INewsContentData newsContentData,
            IPageTemplateSerializeService pageTemplateSerializeService,
            IInitialiseSystemDefineService initialiseSystemDefineService,
            ISerializeMethodService serializeMethodService,
            IHandleSaveFileService handleSaveFileService)
        {
            this.pageTemplateData = pageTemplateData;
            this.newsContentData = newsContentData;
            this.pageTemplateSerializeService = pageTemplateSerializeService;
            this.initialiseSystemDefineService = initialiseSystemDefineService;
            this.serializeMethodService = serializeMethodService;
            this.handleSaveFileService = handleSaveFileService;
        }

        #region 获取系统页面列表
        public IEnumerable<MakeStaticPagingTaskDto> GetSystemPagingList()
        {
            return this.pageTemplateData.Get().As<IEnumerable<MakeStaticPagingTaskDto>>();
        }
        #endregion

        #region 获取分页列表页面模板信息
        public PageTemplateDto GetPagingListInfo(long pageTemplateId)
        {
            PageTemplateEntity pageTemplateEntity = this.pageTemplateData.Get(pageTemplateId);
            if (!pageTemplateEntity.IsPagingListPage)
            {
                throw new ArgumentException("此页面并非分页列表页面!!");
            }
            string pagingListServiceParams = string.Format("{0},{1},{2}", pageTemplateEntity.PagingListServiceParams, 1, pageTemplateEntity.ListSize);
            dynamic result = this.pageTemplateSerializeService.GetServiceMethodResult(pageTemplateEntity.PagingListServiceTag, pagingListServiceParams);
            int total = (int)result.Count;
            int count = total % pageTemplateEntity.ListSize.Value > 0 ? total / pageTemplateEntity.ListSize.Value + 1 : total / pageTemplateEntity.ListSize.Value;
            pageTemplateEntity.TotalPageCount = Convert.ToInt32(count);
            pageTemplateEntity.CurrentlyPageNumber = 1;
            this.pageTemplateData.Update(pageTemplateEntity);
            return pageTemplateEntity.As<PageTemplateDto>();
        }
        #endregion

        #region 获取内容页页面模板信息
        public PageTemplateDto GetContentPagingInfo(long pageTemplateId)
        {
            PageTemplateEntity pageTemplateEntity = this.pageTemplateData.Get(pageTemplateId);
            if (!pageTemplateEntity.IsContentPage)
            {
                throw new ArgumentException("此页面并非内容页面!!");
            }
            string pagingListServiceParams = string.Format("{0},{1},{2}", pageTemplateEntity.PagingListServiceParams, 1, 10000000);
            dynamic result = this.pageTemplateSerializeService.GetServiceMethodResult(pageTemplateEntity.PagingListServiceTag, pagingListServiceParams);
            long total = result.Count;
            pageTemplateEntity.TotalPageCount = Convert.ToInt32(total);
            pageTemplateEntity.CurrentlyPageNumber = 1;
            return pageTemplateEntity.As<PageTemplateDto>();
        }
        #endregion

        #region 构建静态页面
        public string MakeStaticPaging(long pageTemplateId, int? index)
        {
            string html = string.Empty;

            //获取页面模板信息
            PageTemplateEntity pageTemplateEntity = this.pageTemplateData.Get(pageTemplateId);
            Dictionary<string, object> defineData = this.initialiseSystemDefineService.Init();
            if (pageTemplateEntity.IsContentPage)
            {
                string pagingListServiceParams = string.Format("{0},{1},{2}", pageTemplateEntity.PagingListServiceParams, 1, 10000000);
                dynamic result = this.pageTemplateSerializeService.GetServiceMethodResult(pageTemplateEntity.PagingListServiceTag, pagingListServiceParams);
                long total = result.Count;
                IEnumerable<object> items = result.Items as IEnumerable<object>;
                if (!index.HasValue)
                {
                    throw new ArgumentException("未设置生成记录序号!");
                }
                object obj = items.ElementAt(index.Value == 0 ? index.Value : index.Value - 1);
                defineData.Add("&&ContentResult", obj);
                PropertyInfo[] properties = obj.GetType().GetProperties();
                foreach (PropertyInfo propertyInfo in properties)
                {
                    if (propertyInfo.Name == pageTemplateEntity.ContentPageCode)
                    {
                        var dynamicValue = propertyInfo.GetValue(obj, null);
                        if (dynamicValue != null)
                        {
                            defineData.Add("@@" + pageTemplateEntity.ContentPageCode, long.Parse(dynamicValue.ToString()));
                            this.handleSaveFileService.SetContentId(long.Parse(dynamicValue.ToString()));
                        }
                    }
                }

            }

            this.serializeMethodService.ParsePageDefineData(pageTemplateEntity, defineData);
            ParsePageService parsePageService = new ParsePageService(defineData);
            if (pageTemplateEntity.IsPagingListPage)
            {
                if (index.HasValue)
                {
                    pageTemplateEntity.CurrentlyPageNumber = index.Value;
                    html = parsePageService.ParseCommand(pageTemplateEntity.PageHtml);

                    this.pageTemplateData.Update(pageTemplateEntity);
                }
                else
                {
                    html = parsePageService.ParseCommand(pageTemplateEntity.PageHtml);
                    pageTemplateEntity.CurrentlyPageNumber = ++pageTemplateEntity.CurrentlyPageNumber;
                    this.pageTemplateData.Update(pageTemplateEntity);
                }
            }
            else
            {
                html = parsePageService.ParseCommand(pageTemplateEntity.PageHtml);
            }
            html = this.handleSaveFileService.SettingHeadAndAppendAttachments(pageTemplateEntity, html);
            string currentPath = this.handleSaveFileService.GetParentPagePath(pageTemplateEntity);

            //保存Html到文件
            this.handleSaveFileService.SaveHtml(html, currentPath, pageTemplateEntity.PageLevel, pageTemplateEntity.PageUrlName, index);
            parsePageService.Dispose();
            return html;
        }
        #endregion
    }
}
